﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
using RabbitMQ.Client;
using YEA.Infrastructure.Gateway.Config;
using YEA.Infrastructure.Gateway;

namespace YEA.Infrastructure.Gateway.Admin
{
    public class RabbitAdmin
    {
        internal static void InitializeExchanges(Dictionary<string,IConnection> Connections)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var objects = config.GetSection("AMQPAdmin/AMQPObjectsDeclaration") as AMQPObjectsDeclarationSection;
            if (objects != null)
            {
                CreateExchanges(Connections, objects.ExchangeList);
                CreateQueues(Connections, objects.QueueList);
                CreateBindings(Connections, objects.BindingList);
            }
        }

        private static void CreateBindings(Dictionary<string, IConnection> Connections, BindingCollection list)
        {
            Parallel.For(0, list.Count, i =>
            {
                var binding = list[i];
                using (IModel channel = Connections[binding.Connection].CreateModel())
                {
                    channel.QueueBind(binding.Queue, binding.Exchange, binding.SuscriptionKey);
                }
            });
        }

        private static void CreateQueues(Dictionary<string, IConnection> Connections, QueueCollection list)
        {
            Parallel.For(0, list.Count, i =>
            {
                var queue = list[i];
                using (IModel channel = Connections[queue.Connection].CreateModel())
                {
                    channel.QueueDeclare(queue.Name, queue.Durable, queue.Exclusive, queue.AutoDelete, null);
                }
            });
        }

        private static void CreateExchanges(Dictionary<string, IConnection> Connections, ExchangeCollection list)
        {
            Parallel.For(0, list.Count, i =>
            {
                var exchange = list[i];
                using (IModel channel = Connections[exchange.Connection].CreateModel())
                {
                    channel.ExchangeDeclare(exchange.Name, exchange.Type.ToString(), exchange.Durable, exchange.AutoDelete, null);
                }
            });
        }

        
    }
}
